package com.topnav.mc.zzd;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.js.lib.result.Result;
import com.js.lib.utils.DateUtils;
import com.topnav.mc.admin.entity.Device;
import com.topnav.mc.admin.service.IDeviceService;
import com.topnav.mc.zzd.account.ZzdAccountUntil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;
import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: kenny
 * @Date: 2024/1/9 18:01
 */
@RestController
@CrossOrigin
@RequestMapping({"/test/zzd","/zzd"})

public class ZzdGroupUserTreeController {
    @Resource
    public ZzdApiUrl zzdApiUrl;
    @Autowired
    ZzdAccountUntil zzdAccountUntil;
    @Autowired
    private IDeviceService deviceService;

    /**
     * 查询所有群组
     * @param pid
     * @return
     */
    @GetMapping("/find/group/user/tree")
    @ResponseBody
    public DeferredResult<Result> findDeviceForOrgTrue(String pid) {
        String start = DateUtils.format(new Date(),"HH:mm:ss.SSS");
        DeferredResult<Result> result = new DeferredResult<Result>(5000L);
        result.onTimeout(()->{
            result.setResult(Result.error(String.format("超时: %s==>%s",start,DateUtils.format(new Date(),"HH:mm:ss.SSS"))));
        });
        Map<String,Object> map = new HashMap<>();
        map.put("limit",1000);
        map.put("page",0);
        List<GroupUserBean> beans = new ArrayList<>();
        if (!StringUtils.isEmpty(pid)){
            //查群组下的设备
            String[] pids = pid.split("-");
            String groupId=pids[1];
            map.put("group_id",pids[1]);
            String url=zzdApiUrl.queryUser(map);
            ZzdHttpUtil.request(url, null,zzdAccountUntil.getZzdAccount(),new ZzdHttpUtil.ApiCallBack() {
                //群组时的用户查询 成功
                @Override
                public void onResult(String resultJson) {//成功
                    JSONObject json = JSONObject.parseObject(resultJson);
                    JSONObject data = json.getJSONObject("data");
                    Integer total = data.getInteger("total");
                    JSONArray users = (JSONArray)data.get("users");
                    List<String> talkAccounts = new ArrayList<>();
                    for(int i=0;i<users.size();i++){
                        JSONObject jd = (JSONObject)users.get(i);
                        GroupUserBean bean = new GroupUserBean();
                        bean.setId(String.format("U-%s", jd.getString("user_id")));
                        bean.setTitle(jd.getString("user_name"));
                        bean.setOnline(jd.getString("user_online"));
                        bean.setType("usr");
                        bean.getArrt().put("id",jd.getString("user_id"));
                        bean.getArrt().put("name",jd.getString("user_name"));
                        bean.getArrt().put("groupId",groupId);
                        bean.getArrt().put("userAccount",jd.getString("user_account"));
                        bean.getArrt().put("groupIds",jd.getString("group_ids"));
                        bean.getArrt().put("userId",jd.getString("user_id"));
                        talkAccounts.add(jd.getString("user_account"));
                        beans.add(bean);
                    }
                    //取设备的数据
                    if (talkAccounts.size() > 0){
                        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper();
                        wrapper.in(Device::getTalkAccount,talkAccounts);
                        List<Device> devices = deviceService.list(wrapper);
                        for(Device device : devices){
                            for(GroupUserBean bean: beans){
                                if (device.getTalkAccount().equals(bean.getArrt().get("userAccount"))){
                                    bean.getArrt().put("deviceCode",device.getCode());
                                    bean.getArrt().put("deviceName",device.getName());
                                    bean.getArrt().put("deviceId",device.getId());
                                    break;
                                }
                            }
                        }
                    }
                    result.setResult(Result.ok(beans));
                }
            },  new ZzdHttpUtil.ApiCallBack() {
                //群组里的用户查询 失败
                @Override
                public void onResult(String resultJson) {//失败
                    System.out.println(resultJson);
                    result.setResult(ZzdHttpUtil.genResult(resultJson));
                }
            });
        }else{
          //群组查询
            String url=zzdApiUrl.queryGroup(map);
            ZzdHttpUtil.request(url, null,zzdAccountUntil.getZzdAccount(),new ZzdHttpUtil.ApiCallBack() {
                @Override
                public void onResult(String resultJson) {//成功
                    JSONObject json = JSONObject.parseObject(resultJson);
                    JSONObject data = json.getJSONObject("data");
                    Integer total = data.getInteger("total");
                    JSONArray groups = (JSONArray)data.get("groups");

                    for(int i=0;i<groups.size();i++){
                        JSONObject jd = (JSONObject)groups.get(i);
                        GroupUserBean bean = new GroupUserBean();
                        bean.setId(String.format("G-%s", jd.getString("group_id")));
                        bean.setTitle(jd.getString("group_name"));
                        bean.setType("grp");
                        bean.setChildren(new ArrayList<>());
                        bean.getArrt().put("groupId",jd.getString("group_id"));
                        bean.getArrt().put("id",jd.getString("group_id"));
                        bean.getArrt().put("name",jd.getString("group_name"));
                        beans.add(bean);
                    }
                    //System.out.println(resultJson);
                    result.setResult(Result.ok(beans));
                }
            },  new ZzdHttpUtil.ApiCallBack() {
                //错误
                @Override
                public void onResult(String resultJson) {//失败
                    System.out.println(resultJson);
                    result.setResult(ZzdHttpUtil.genResult(resultJson));
                }
            });
        }
        return result;
    }
}
